

auto.waitFor()
const autojsUtils = require('./modules/autojs-utils')
require("./modules/config.js")
var img_url = config.icon
//随机数字
function getRandomInt(min, max) {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min + 1)) + min;
}
let num = getRandomInt(1,10000)

window = floaty.rawWindow(
    <horizontal gravity="center_vertical">
        <img id="floaty_icon" src="{{img_url}}" w="40" h="40" alpha="0.8" circle="true" borderWidth="1dp" borderColor="black" />
        <text id="text">当前:{num}</text>
        <horizontal id="h_drawer">
            <vertical>
                <button id="ui_start_server" textColor="#FFFFFF" text="启动" bg="#4F4F4F" padding="0" h="40" w="50" />
				<text text="" h="1" />
                <button id="ui_start" textColor="#FFFFFF" text="查询金额" bg="#4F4F4F" padding="0" h="40" w="50" />
				<text text="" h="1" />
                <button id="ui_other_start" textColor="#FFFFFF" text="下注" bg="#4F4F4F" padding="0" h="40" w="50" />
                <text text="" h="1" />
                <button id="ui_close" textColor="#FFFFFF" text="结束" bg="#4F4F4F" padding="0" h="40" w="50" />
            </vertical>
        </horizontal>
    </horizontal>
);
window.setPosition(50, device.height / 3);
window.exitOnClose();

window.h_drawer.visibility = 8;


var execution = null;
var x = 0,
    y = 0;
var windowX, windowY;
var downTime;
console.log("w=" + device.width);
console.log("h=" + device.height);
window.floaty_icon.setOnTouchListener(function (view, event) {
    switch (event.getAction()) {
        case event.ACTION_DOWN:
            x = event.getRawX();
            y = event.getRawY();
            windowX = window.getX();
            windowY = window.getY();
            downTime = new Date().getTime();
            return true;
        case event.ACTION_MOVE:
            //移动手指时调整悬浮窗位置
            let movexx = windowX + (event.getRawX() - x);
            let moveyy = windowY + (event.getRawY() - y);
            if (movexx < 0 || movexx > device.width) {
                movexx = 0;
            }

            if (moveyy < 0 || moveyy > device.height) {
                moveyy = 0;
            }
            window.setPosition(movexx, moveyy);
            console.log("event y=" + event.getRawY());
            console.log("event x=" + event.getRawX());
            return true;
        case event.ACTION_UP:
            if (Math.abs(event.getRawY() - y) < 5 && Math.abs(event.getRawX() - x) < 5) {
                drawerStatus();
            }
            return true;
    }
    return true;
});

function drawerStatus() {
    if (window.h_drawer.visibility == 8) {
        window.h_drawer.visibility = 0;
    } else {
        window.h_drawer.visibility = 8;
    }
}
//运行按钮事件
window.ui_start_server.setOnTouchListener(function (view, event) {
    let startKey = "启动"
    let ingKey = "运行中"
    if (event.getAction() == event.ACTION_UP) {
        window.setPosition(50, device.height / 3);
        window.disableFocus();
        if (window.ui_start_server.text() == startKey) {
            window.ui_start_server.text(ingKey);

            let main = threads.start(function () {
                device.keepScreenOn()
                //运行脚本
                //todo 在这里运行你的脚本
                startServer(startKey)
            })

            //两秒不点击暂停，则隐藏抽屉
            setTimeout(function () {
                if (window.ui_start_server.text() == ingKey) {
                    drawerStatus()
                }
            }, 2000)

            //监控运行还是暂停
            var monitoringStatus = setInterval(function () {
                if (window.ui_start_server.text() == startKey) { //是运行说明暂停了
                    try{
                        wsObj.close()
                    }catch(err){
                        console.error('WebSocket 关闭失败');
                        console.error(err);
                    }
                    try{
                        threadTask.interrupt()
                    }catch(err){
                        console.error(err);
                    }
                    main.interrupt()
                    toastLog(startKey+"已暂停");
                    clearInterval(monitoringStatus)
                }
            }, 100)
        } else {
            toastLog(startKey+"暂停中...");
            window.ui_start_server.text(startKey);
        }
    }
    return true;
});
//运行按钮事件
window.ui_start.setOnTouchListener(function (view, event) {
    let startKey = "查询金额"
    let ingKey = "查询金额运行中"
    if (event.getAction() == event.ACTION_UP) {
        window.setPosition(50, device.height / 3);
        window.disableFocus();
        if (window.ui_start.text() == startKey) {
            window.ui_start.text(ingKey);

            let main = threads.start(function () {
                device.keepScreenOn()
                //运行脚本
                //todo 在这里运行你的脚本
                onClick()
				window.ui_start.text(startKey);
            })

            //两秒不点击暂停，则隐藏抽屉
            setTimeout(function () {
                if (window.ui_start.text() == ingKey) {
                    drawerStatus()
                }
            }, 2000)

            //监控运行还是暂停
            var monitoringStatus = setInterval(function () {
                if (window.ui_start.text() == startKey) { //是运行说明暂停了
                    main.interrupt()
                    toastLog(startKey+"已暂停");
                    clearInterval(monitoringStatus)
                }
            }, 100)
        } else {
            toastLog(startKey+"暂停中...");
            window.ui_start.text(startKey);
        }
    }
    return true;
});
//运行按钮事件
window.ui_other_start.setOnTouchListener(function (view, event) {
    let startKey = "下注"
    let ingKey = "下注运行中"
    if (event.getAction() == event.ACTION_UP) {
        window.setPosition(50, device.height / 3);
        window.disableFocus();
        if (window.ui_other_start.text() == startKey) {
            window.ui_other_start.text(ingKey);

            let main = threads.start(function () {
                device.keepScreenOn()
                //运行脚本
                //todo 在这里运行你的脚本
                onFeedback()
				window.ui_other_start.text(startKey);
            })

            //两秒不点击暂停，则隐藏抽屉
            setTimeout(function () {
                if (window.ui_other_start.text() == ingKey) {
                    drawerStatus()
                }
            }, 2000)

            //监控运行还是暂停
            var monitoringStatus = setInterval(function () {
                if (window.ui_other_start.text() == startKey) { //是运行说明暂停了
                    main.interrupt()
                    toastLog(startKey+"已暂停");
                    clearInterval(monitoringStatus)
                }
            }, 100)

        } else {
            toastLog(startKey+"暂停中...");
            window.ui_other_start.text(startKey);
        }
    }
    return true;
});

//启用按键监听
events.observeKey();

events.on("key", function (code, event) {
    threads.shutDownAll();
});

window.ui_close.setOnTouchListener(function (view, event) {
    if (event.getAction() == event.ACTION_UP) {
		if (window.ui_close.text() == "结束") {
            try {
                wsObj.close()
            } catch (err) {
                console.error('WebSocket 关闭失败');
                console.error(err);
            }
			window.ui_close.text("结束中");
			threads.shutDownAll();
			window.close();
			exit();
		}
    }
    return true;
});
let threadTask = null
let wsObj = null
function startServer(startKey){
    console.log("开始连接服务器...")
    //根据指令进行操作 不能阻塞进程
    //链接服务器wss://192.168.1.10:8080/
    let wssUrl = "ws://192.168.0.175:8080/ws"
    
    wsObj = new WebSocket(wssUrl);
    wsObj.on(WebSocket.EVENT_OPEN, (res, ws) => {
        console.log('WebSocket 已连接',res);
        wsObj.send(JSON.stringify({
            title: getTitle(),
            num: num,
            init: 1
        }))
    })
    .on(WebSocket.EVENT_TEXT, (text, ws) => {
        if(text == "ok"){
            toastLog("连接成功");
            return
        }
        let msg = JSON.parse(text)
        if (msg.type === 'ping') {
            return;
        }
        console.log("收到服务器消息: " + text);
        if (msg.instruction == "get") {
            try{
                let money = getMoney()
                //发送查询结果
                wsObj.send(JSON.stringify({
                    instruction: "get",
                    money: money,
                    title: getTitle(),
                    num: num,
                }))
            }catch(err){
                console.error('查询失败');
                console.error(err);
            }
        } else if (msg.instruction == "set") {
            try{
                dowMoney(msg.text, msg.money)
                //发送下注结果
                wsObj.send(JSON.stringify({
                    instruction: "set",
                    money: getMoney(),
                    title: getTitle(),
                    num: num,
                }))
            }catch(err){
                console.error('下注失败');
                console.error(err);
            }
        } else if (msg.instruction == "getTime") {
            try{
                let timeNum = getTime()
                //发送下注结果
                wsObj.send(JSON.stringify({
                    instruction: "getTime",
                    timeNum: timeNum,
                    title: getTitle(),
                    num: num,
                }))
            }catch(err){
                console.error('下注失败');
                console.error(err);
            }
        }
    })
    .on(WebSocket.EVENT_CLOSING, (code, reason, ws) => {
        console.log('WebSocket 关闭中');
    })
    .on(WebSocket.EVENT_CLOSED, (code, reason, ws) => {
        console.log('WebSocket 已关闭');
        console.log(`code: ${code}`);
        if (reason) console.log(`reason: ${reason}`);
        
		window.ui_start_server.text(startKey);
		threadTask.interrupt()
    })
    .on(WebSocket.EVENT_FAILURE, (err, res, ws) => {
        console.error('WebSocket 连接失败');
        console.error(err);
        
		window.ui_start_server.text(startKey);
		threadTask.interrupt()
    });
    wsObj.send(JSON.stringify({type: 'pong'}));
    //设置一个空的定时来保持线程的运行状态
    setInterval(function () {
        wsObj.send(JSON.stringify({type: 'pong'}));
    }, 2000);
}

function onClick() {
    getMoney()
}
function getTitle(){
	//等待进入主界面
	id("tv_money").waitFor()
	//刷新钱
    return id("tv_room_name").findOne().text()
}
function getMoney(){
	//等待进入主界面
	id("tv_money").waitFor()
	//刷新钱
	id("tv_refresh_money").findOne().click()
    sleep(2000)
    //获取当前钱
	let tvmoney = id("tv_money").findOne()
    let money = tvmoney.text()
    console.log("money=" + money)
    toastLog(money);
    sleep(2000)
    return money
}
function getTime(){
    let tv_time = id("tv_time").findOne()
    let time = tv_time.text()
    return time
}
function dowMoney(text,money){
	//等待进入主界面
	id("tv_money").waitFor()
	if(id("tv_tips").exists() && id("tv_tips").findOne().text() == "封盘中禁止下注"){
        toastLog("当前已禁止下注");
        sleep(2000)
        return
    }
    //下注
    let et_lottery = id("et_lottery").findOne()
    et_lottery.setText(text+money)
    sleep(1000)
    //发送
    id("tv_send").findOne().click()
    sleep(2000)
    //没钱会提示"余额不足"
    if(id("content").className("android.widget.TextView").exists()){
        let content = id("content").className("android.widget.TextView").findOne()
        toastLog(content.text())
        id("cancle").findOne().click()
        sleep(2000)
    }
    return
}

function onFeedback() {
    dowMoney("大",100)
}
